﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace GrayParrot.Infrastructure.Menu
{
    public class NodeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(MenuItem));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            MenuItem node = (MenuItem)value;
            JObject jo = new JObject();
            jo.Add("id", node.MenuId);
            jo.Add("name", node.Name);
            jo.Add("iconPath", node.IconPath);
            jo.Add("tooltip", node.Tooltip);
            jo.Add("index", node.Index);
            jo.Add("parentId", node.ParentId);
            jo.Add("url", node.Url);
            jo.Add("controller", node.Controller);

            if (node.Childs.Count == 0)
            {
                jo.Add("leaf", true);
            }
            else
            {
                jo.Add("children", JArray.FromObject(node.Childs, serializer));
            }

            jo.WriteTo(writer);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}
